<template>
    <div style="background: white">
        <div v-if="resultList.length>0" style="margin-top: 30px;padding-top: 5px">
            <a-breadcrumb separator=">" style="margin: 10px">
                <a-breadcrumb-item v-for="(filter,i) in searchRequest.filterOptions">

                    <a-button type="link" class="selected-param selected-param-hover" size="small"
                              @click="removeSelectedParam(i)">
                        {{filter.name==='brandId'?'品牌':filter.name==='cid3'?'分类':filter.name}}：<span
                            style="color: #EA7979">{{filter.name==='cid3'||filter.name==='brandId'?filter.label.join("、"):filter.values.join("、")}}</span>
                        <a-icon type="close"/>
                    </a-button>

                </a-breadcrumb-item>
            </a-breadcrumb>
            <a-card class="cate23Card">
                <!--品牌-->
                <a-row class="param-row" v-for="(param,index) in brandCateParams" :key="index"
                       v-if="param.name==='品牌'">
                    <a-col :span="3">
                        <span>{{param.name}}：</span>
                    </a-col>
                    <a-col :span="20">
                        <a-card v-if="!param.multi">
                            <a-card-grid v-for="value in param.values" :key="value.id"
                                         style="padding:12px 0px 6px 0px;width:12.8%;height:55px;text-align:center">
                                <div v-if="value.logo">
                                    <a @click="addFilter('brandId',false,value.id,value.name)">
                                        <img style="height: 100%" :src="value.logo"/></a>
                                </div>
                                <div v-else>
                                    <a class="param-item" @click="addFilter('brandId',false,value.id,value.name)">{{value.name}}</a>
                                </div>
                            </a-card-grid>

                        </a-card>
                        <div v-if="param.multi">
                            <a-card-grid :class="brandItemStyle[bi]===true?'brand-grid-selected':'brand-grid'"
                                         v-for="(value,bi) in param.values" :key="value.id">
                                <a v-if="value.logo"><img
                                        @click="multiSelect('brandId',false,value,bi)"
                                        style="height: 100%"
                                        :src="value.logo"/>
                                </a>
                                <a v-else @click="multiSelect('brandId',false,value,bi)"
                                >{{value.name}}</a>
                            </a-card-grid>
                            <div style="text-align: center">
                                <a-button v-if="param.multi&&multiSelected.name"
                                          style="background: red;color: white" type="link"
                                          @click=" clickMulti(param,index)">确认
                                </a-button>
                                <a-button style="color: #868686" type="link"
                                          @click="cancelMulti(param,index)">取消
                                </a-button>
                            </div>
                        </div>
                    </a-col>
                    <a-col v-if="!param.multi" :span="1">
                        <a-button type="link" style="float: right" @click="param.multi=true">多选
                        </a-button>
                    </a-col>
                </a-row>
                <!--分类-->
                <a-row class="param-row" v-for="(param,index) in brandCateParams" :key="index"
                       v-if="param.name==='分类'">
                    <a-col :span="3">
                        <span class=" spec-name">{{param.name}}：</span>
                    </a-col>
                    <a-col :span="21">
                        <a type="link" class="param-item" @click="addFilter('cid3',false,value.id,value.name)"
                           v-for="value in param.values" :key="value.id">
                            {{value.name}}
                        </a>

                    </a-col>

                </a-row>
                <!--规格-->
                <div>
                    <a-row class="param-row" v-for="(param,specIndex) in specParams" :key="param.name"
                           v-show="specIndex<5 || showSpecAll"
                    >
                        <a-col :span="3">
                            <span class=" spec-name">{{param.name}}：</span>
                        </a-col>
                        <div>
                            <a-col :span="20" style="vertical-align: center">
                                <a v-if="!param.multi" type="link" class="param-item"
                                   @click="addFilter(param.name,param.text,value,null)"
                                   v-for="(value,pinx) in param.values" :key="value" v-show="param.more || pinx<13">
                                    {{value}}
                                </a>
                                <div>
                                    <div>
                                        <a-checkbox-group
                                                v-if="param.multi"
                                                :options="param.values"
                                                @change="checkedValues=>multiSelect(param.name,param.text,checkedValues,null)"
                                        />
                                    </div>
                                    <div v-if="param.multi" style="text-align: center">
                                        <a-button v-if="param.multi&&multiSelected.name"
                                                  style="background: red;color: white" type="link"
                                                  @click=" clickMulti(param,specIndex)">确认
                                        </a-button>
                                        <a-button style="color: #868686" type="link"
                                                  @click="cancelMulti(param,specIndex)">取消
                                        </a-button>
                                    </div>
                                </div>

                            </a-col>

                            <a-col v-if="!param.multi" :span="1">
                                <a-button type="link" style="float: right" @click="param.multi=true">多选
                                </a-button>
                            </a-col>

                            <a-col v-if="param.values.length>13&&param.more===false" :span="1">
                                <a-button type="link" style="float: right" @click="param.more=true">更多
                                </a-button>
                            </a-col>
                            <a-col v-if="param.more" :span="1">
                                <a-button type="link" style="float: right" @click="param.more=false">收起
                                </a-button>
                            </a-col>
                        </div>
                    </a-row>
                    <a-divider></a-divider>
                    <div class="expanDiv" style="text-align: center;horiz-align: center;color: black">
                        <a class="expand-collapsed" v-show="!showSpecAll" @click="showSpecAll=true">打开 ↓</a>

                        <a class="expand-collapsed" v-show="showSpecAll" @click="showSpecAll=false">收起 ↑</a>
                    </div>
                </div>

            </a-card>
        </div>

        <div>

            <a-radio-group v-model="searchRequest.sortField" @change="search">
                <a-radio value="sellCount">销量</a-radio>
                <a-radio value="priceList">单价</a-radio>
                <a-radio value="createTime">新品</a-radio>
            </a-radio-group>
            <a-row :gutter="[24,3]">
                <a-col v-if="resultList.length>0" :span="4" v-for="(goods,index) in resultList" :key="goods.id">
                    <a-card hoverable style="width: 240px;height:460px;padding:12px 4px;overflow: auto;"
                            @click="toDetail(goods)"

                    >
                        <img
                                @click="toDetail(goods)"
                                slot="cover"
                                alt="example"
                                :src="goods.selectedSku.picture"/>
                        <div>
                            <img class="sku-image" :style="goods.selectedSku.id===sku.id?'border: 1px solid red':''"
                                 @mouseover="selectSku(index,sku)"
                                 @click="toDetail(goods)"
                                 v-for="(sku,skuIndex) in goods.goodsSkus"
                                 :src="sku.picture"/>
                        </div>

                        <div class="sku-title-tool">
                            <a-tooltip placement="rightBottom">
                                <template slot="title">
                                    <span>{{goods.selectedSku.name}}</span>
                                </template>
                                <a v-if="goods.selectedSku.name.toLowerCase().indexOf(searchRequest.key.toLowerCase())>-1">
                                    <a class="sku-title">{{goods.selectedSku.name.substring(0,goods.selectedSku.name.toLowerCase().indexOf(searchRequest.key.toLowerCase())).length<=50 ?
                                        goods.selectedSku.name.substring(0,
                                        goods.selectedSku.name.toLowerCase().indexOf(searchRequest.key.toLowerCase()))
                                        :goods.selectedSku.name.substring(0,goods.selectedSku.name.toLowerCase().indexOf(searchRequest.key.toLowerCase())).substring(0,50)}}</a>
                                    <a class="sku-title" style="color: red">{{goods.selectedSku.name.substr(goods.selectedSku.name.toLowerCase().indexOf(searchRequest.key.toLowerCase()),searchRequest.key.length)}}</a>
                                    <a class="sku-title">{{goods.selectedSku.name.substring(goods.selectedSku.name.toLowerCase().indexOf(searchRequest.key.toLowerCase())+searchRequest.key.length)}}</a>
                                </a>
                                <a v-else>
                                    <a class="sku-title">{{goods.selectedSku.name.length>50?goods.selectedSku.name.substring(0,50)+'...':goods.selectedSku.name}}</a>
                                </a>

                            </a-tooltip>
                        </div>


                        <!--        <div class="sku-subName">
                                    {{goods.subName.length>40?goods.subName.substring(0,30)+'...':goods.subName}}
                                </div>-->

                        <div style="color: #E01222">
                            ￥
                            <span style="font-size: 24px;display: inline-block">
                               {{ goods.selectedSku.price}}
                                <!--                                <a-button style="display: inline-block; float:right;margin-left: 5px; border:none;background: #E01222;color: white">立即抢购</a-button>-->
                            </span>
                        </div>
                        <div style="color: #b3b3b3;font-size: 13px;">
                            {{goods.shopName}}
                            <a-icon style="margin-left: 15px" type="aliwangwang" theme="filled"/>
                        </div>
                    </a-card>
                </a-col>


                <a-col :span="24">
                    <a-empty style="height: 600px;margin-top: 20px" v-if="resultList.length<=0"/>
                </a-col>
            </a-row>

            <a-pagination
                    style="margin: 20px;float: right"
                    v-model="searchRequest.page"
                    show-quick-jumper
                    :total="total"
                    :page-size="searchRequest.size"
                    @change="pageChange"
            >
            </a-pagination>


        </div>
    </div>
</template>

<script>
    import {getUrlParam} from "../../utils/urlUtils";
    import SearchApi from "../../api/search/SearchApi";
    import searchHistoryApi from "../../api/info/searchHistoryApi";
    import Cookies from "js-cookie";

    export default {
        name: "SearchApp",
        data() {
            return {
                searchRequest: {
                    cid3: -1,
                    key: "",
                    sortField: "sellCount",
                    filterOptions: [], //过滤条件
                    page: 1,
                    size: 100
                },
                resultList: [],//商品集
                brandCateParams: [], //品牌和分类参数
                specParams: [], //过滤搜索的参数们

                total: 0,
                pageSizeOptions: ['3', '5', '10', '20', '30'],
                showSpecAll: false,//是否展示全部参数
                // paramMore: [],//控制参数是否展示更多
                multiSelected: {name: "", text: false, values: [], label: []},// 多选时暂存选择的参数 点击确定或取消时清除
                brandItemStyle: []

            }
        },
        created() {
            let urlParam = getUrlParam();
            if (urlParam.cid3) {
                this.searchRequest.cid3 = urlParam.cid3
                this.search()

            } else if (urlParam.key) {
                this.searchRequest.key = urlParam.key
                this.search()
            }
        },
        watch: {


            /**
             * 监听地址变化
             */
            "$route"(to, from) {
                if (to.query.key) {
                    this.initSearchRequest()
                    if (this.searchRequest.key !== to.query.key) {
                        this.searchRequest.key = to.query.key
                        this.addHistory()
                    } else {
                        this.searchRequest.key = to.query.key
                    }
                    this.search()
                }

            }
        },
        methods: {

            toDetail(goods) {
                console.log(goods)
                let uri = `/goodDetail?goodsInfo=${encodeURI(JSON.stringify({
                    id: goods.id,
                    index: goods.selectedSku.specIndexes
                }))}`
                this.$router.push(encodeURI(uri))
            },
            removeSelectedParam(index) {
                this.searchRequest.filterOptions.splice(index, 1)
                this.search()
            },
            /**
             *  确认多选
             */
            clickMulti(param, SpecIndex) {
                if (this.multiSelected.name) {
                    //当前参数之外的所有已选过滤项
                    let newFilters = this.searchRequest.filterOptions.filter(o => {
                        return o.name !== this.multiSelected.name
                    });
                    if (param.name === '品牌') {
                        this.brandCateParams[SpecIndex].multi = false;
                    } else {
                        this.specParams[SpecIndex].multi = false;
                    }
                    newFilters.push(this.multiSelected);
                    this.searchRequest.filterOptions = newFilters
                    this.search()
                    this.multiSelected = {}
                    this.brandItemStyle = []

                }
            },
            cancelMulti(param, SpecIndex) {
                console.log(param)
                if (param.name === '品牌') {
                    this.brandCateParams[SpecIndex].multi = false;
                } else {
                    this.specParams[SpecIndex].multi = false;
                }
                this.multiSelected = {}
                this.brandItemStyle = []
            },
            /**
             * 多选选择的回调
             * @param paramName 参数名
             * @checkedValue 选中的值
             */
            multiSelect(paramName, text, checkedValues, index) {
                if (paramName === "brandId") {
                    let item = {
                        name: paramName,
                        text: text,
                        values: [checkedValues.id],
                        label: [checkedValues.name]
                    }
                    if (this.multiSelected.name === paramName) {
                        if (this.brandItemStyle[index] === true) { //当前品牌已经选择 则为取消选择操作
                            this.brandItemStyle[index] = false;
                            //过滤掉当前品牌后重新赋值
                            item.values = this.multiSelected.values.filter(s => s !== checkedValues.id)
                            item.label = this.multiSelected.label.filter(s => s !== checkedValues.name)
                        } else {
                            //否则为选择操作
                            this.brandItemStyle[index] = true;
                            let newSelectedValues = []
                            let newSelectedLabel = []
                            Object.assign(newSelectedValues, this.multiSelected.values)
                            Object.assign(newSelectedLabel, this.multiSelected.label)
                            newSelectedValues.push(checkedValues.id)
                            newSelectedLabel.push(checkedValues.name)
                            item.values = newSelectedValues
                            item.label = newSelectedLabel
                        }
                    } else {
                        this.brandItemStyle[index] = true
                    }
                    this.multiSelected = item


                } else {
                    this.multiSelected = {name: paramName, text: text, values: checkedValues}
                }
            },
            /**
             *  选择过滤条件
             */
            addFilter(paramName, text, value, label) {
                //先过滤掉已经清除的目标参数
                let newFilters = this.searchRequest.filterOptions.filter(o => {
                    return o.name !== paramName
                });
                let filter = {name: paramName, text: text, values: [value]}
                if (label) {
                    //品牌和分类的名称
                    filter.label = [label];
                }
                newFilters.push(filter);
                this.searchRequest.filterOptions = newFilters
                this.search()
            },

            pageChange(value) {
                this.searchRequest.page = value;
                this.search()
            },
            search() {
                SearchApi.search(this.searchRequest).then(resp => {
                    let goodsList = resp.data.rows;
                    goodsList.forEach(goods => {
                        goods.goodsSkus = JSON.parse(goods.goodsSkus)
                        goods.goodsSkus.forEach(sku => {
                            if ((sku.price + '').indexOf(".") <= 0) {
                                sku.price = sku.price + ".00"
                            }
                        })
                        if (goods.goodsSkus.length > 5) {
                            goods.goodsSkus = goods.goodsSkus.splice(0, 5)
                        }
                        goods.selectedSku = goods.goodsSkus[0];
                    })
                    this.resultList = goodsList;
                    console.log(this.resultList)
                    this.total = resp.data.total / this.searchRequest.size;
                    this.brandCateParams = []
                    if (resp.data.brandList.length > 0) {
                        this.brandCateParams.push({name: "品牌", values: resp.data.brandList, more: false, multi: false})
                    }
                    if (resp.data.categoryList.length > 0) {
                        this.brandCateParams.push({name: "分类", values: resp.data.categoryList})
                    }
                    this.specParams = []
                    resp.data.searchParamList.forEach(searchParam => {
                        searchParam.more = false;
                        searchParam.multi = false;
                        this.specParams.push(searchParam)
                    })

                })
            },
            /**
             * 选中sku
             */
            selectSku(index, selectedSku) {
                console.log(selectedSku)
                this.resultList[index].selectedSku = selectedSku
            },
            initSearchRequest() {
                this.searchRequest.cid3 = -1;
                this.searchRequest.key = "",
                    this.searchRequest.filterOptions = [], //过滤条件
                    this.searchRequest.page = 1,
                    this.searchRequest.size = 100
            },
            addHistory() {
                console.log(this.searchRequest.key)
                const token = Cookies.get("user_token_web");
                if (token) {
                    if (this.searchRequest.key && this.searchRequest.key !== "undefined" && this.searchRequest.key.trim() !== "") {
                        searchHistoryApi.addHistory(this.searchRequest.key).then(resp => {
                            console.log(resp.data)
                        })
                    }
                }

            }
        }
    }
</script>

<style scoped>

    .brand-grid {
        padding: 12px 0px 6px 0px;
        width: 12.8%;
        height: 55px;
        text-align: center
    }

    .brand-grid-selected {
        padding: 12px 0px 6px 0px;
        width: 12.8%;
        height: 55px;
        text-align: center;
        border: 1px solid red;
    }

    .sku-image {
        height: 25px;
        width: 25px;
        margin-right: 5px;
    }

    .sku-title {
        font-size: 12px;
        color: #868686
    }

    .sku-title-tool :hover {
        color: #ef601d;
    }

    .sku-subName {
        font-size: 11px;
        color: #868686;
        margin-top: 5px;
    }

    .param-item:hover {
        color: #f36828;

    }

    .param-item {
        color: #4F83B8;
        font-size: 13px;
        height: 16px;
        margin: 0px 35px 10px 5px;

    }

    .spec-name {
        font-weight: bold;
    }

    .expand-collapsed {
        margin: 13px;
        color: black;
    }

    .expand-collapsed :hover {
        color: #ef601d;
    }

    .expanDiv :hover {
        color: #ef601d;
    }

    .param-row {
        padding-bottom: 5px;
        vertical-align: center;
        margin: 0 10px 10px 10px;
        border-bottom: 1px solid #e3e3e3;
    }

    .selected-param {
        color: #6B6B6B;
        border: 1px solid #DDDDDD;
        background: #F3F3F3;
        font-size: 12px;
    }

    .selected-param-hover:hover {
        background: white;
        border-color: #E01222;
    }
</style>